package com.crayfish.quduo.ui.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.crayfish.quduo.R;
import com.crayfish.quduo.model.NewsBean;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：crayfish(徐杰)
 * 描述：
 * Created by crayfish on 2017/3/30.
 */
public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener{

    private List<NewsBean> datas;

    public NewsAdapter() {
        super();
        this.datas = new ArrayList<NewsBean>();
    }

    public void clear(){
        this.datas.clear();
        notifyDataSetChanged();
    }

    public void addAll(List<NewsBean> newsBeanList){
        this.datas.addAll(newsBeanList);
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news,parent,false);
        NormalViewHolder holder = new NormalViewHolder(view);
        view.setOnClickListener(this);
        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ((NormalViewHolder)holder).txt_title.setText(datas.get(position).getTitle());
        ((NormalViewHolder)holder).txt_time.setText(datas.get(position).getCreatedAt());
        ((NormalViewHolder)holder).itemView.setTag(datas.get(position));
    }

    @Override
    public void onClick(View v) {
        if(onRecyclerViewItemClickListener != null){
            onRecyclerViewItemClickListener.onItemClick(v,(NewsBean)v.getTag());
        }
    }

    static class NormalViewHolder extends RecyclerView.ViewHolder{
        TextView txt_title;
        TextView txt_time;

        public NormalViewHolder(View itemView) {
            super(itemView);
            txt_title = (TextView)itemView.findViewById(R.id.txt_title);
            txt_time = (TextView)itemView.findViewById(R.id.txt_time);
        }
    }

    public OnRecyclerViewItemClickListener onRecyclerViewItemClickListener;

    public void setOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener listener){
        this.onRecyclerViewItemClickListener = listener;
    }

    public interface OnRecyclerViewItemClickListener{
        void onItemClick(View v,NewsBean item);
    }
}
